package com.blobfish.fiction.common.pageprocessor;

import com.blobfish.fiction.common.pipeline.XicidailiPipeline;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.ArrayList;
import java.util.List;

/**
 * 国内高匿代理IP
 */
public class XicidailiPageProcessor implements PageProcessor {
    /**
     * 节点
     */
    private Site site = Site.me().setRetryTimes(10).setSleepTime(3000);

    @Override
    public void process(Page page) {
        //page.getHtml().xpath("//table[@id=\"ip_list\"]/tbody/tr/td/regex(\"((25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\")");
        //page.getHtml().xpath("//table[@id=\"ip_list\"]/tbody/tr/td/regex(\"\\d+\")");
        List<String> contents = page.getHtml().xpath("//table[@id=\"ip_list\"]/tbody/tr/td/text()").all();
        List<String> ipList = new ArrayList();
        for (int i = 0; i < contents.size(); i++) {
            if (i % 10 == 1) {
                ipList.add(i / 10, contents.get(i) + ":" + contents.get(i + 1));
                ++i;
            }
        }
        page.putField("ipList", ipList);
        // page.addTargetRequests(page.getHtml().links().regex("(http://www.xicidaili.com/\\w+/\\w+)").all());
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        //InitPluginUtil.getInstance().initDatabasePlugin();
        Spider.create(new XicidailiPageProcessor())
                .addPipeline(new XicidailiPipeline())
                .addUrl("http://www.xicidaili.com/wn/1",
                        "http://www.xicidaili.com/wn/2",
                        "http://www.xicidaili.com/wn/3",
                        "http://www.xicidaili.com/wn/4",
                        "http://www.xicidaili.com/wn/5",
                        "http://www.xicidaili.com/wn/6",
                        "http://www.xicidaili.com/wn/7",
                        "http://www.xicidaili.com/wn/8",
                        "http://www.xicidaili.com/wn/9",
                        "http://www.xicidaili.com/wn/10",
                        "http://www.xicidaili.com/wt/1",
                        "http://www.xicidaili.com/wt/2",
                        "http://www.xicidaili.com/wt/3",
                        "http://www.xicidaili.com/wt/4",
                        "http://www.xicidaili.com/wt/5",
                        "http://www.xicidaili.com/wt/6",
                        "http://www.xicidaili.com/wt/7",
                        "http://www.xicidaili.com/wt/8",
                        "http://www.xicidaili.com/wt/9",
                        "http://www.xicidaili.com/wt/10").thread(10).run();
    }
}
